package org.example.com.scheduled;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.com.Bean.ShoppingCart;
import org.example.com.mapper.ShoppingCartMapper;
import org.example.com.service.ShoppingCartService;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class CopyScheduled {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ShoppingCartService service;
    @Resource
    private ShoppingCartMapper mapper;
    @Scheduled(cron = "0 53 17 * * ?")
    public void copy() {
        log.info("开始备份");
        mapper.clearShoppingCart();
        HashOperations<String, Object, Object> ops = stringRedisTemplate.opsForHash();
        Set<String> keys=stringRedisTemplate.keys("gwc:*");
        keys.forEach(key -> {
            String userId=key.replace("gwc:","");
            Map<Object,Object> entries = ops.entries(key);
            entries.keySet().forEach(bookId->{
                int number=Integer.parseInt(entries.get(bookId).toString());
                ShoppingCart sc=new ShoppingCart();
                sc.setId(bookId.toString());
                sc.setNumber(number);
                sc.setUserId(userId);
                service.save(sc);
            });
        });
    }
}
